using System.Linq;
using System.Windows.Forms;
using Greg.XmlEditor.Presentation.Presenters;

namespace Greg.XmlEditor.Presentation.Commands.Concrete
{
	public class ExitCommand : CommandBase
	{
		private readonly MasterPresenter presenter;
		private readonly IInteractionManager interaction;

		public ExitCommand(MasterPresenter presenter, IInteractionManager interaction)
		{
			this.presenter = presenter;
			this.interaction = interaction;
		}

		/// <summary>
		/// Refreshes the command state.
		/// </summary>
		public override void Refresh()
		{
			this.IsEnabled = true;
		}

		/// <summary>
		/// Executes the command logics.
		/// </summary>
		public override void Invoke()
		{
			if (!this.presenter.Documents.Any(d => d.IsDirty))
			{
				Application.Exit();
			}

			// salvare i cambiamenti ai files
			if (this.presenter.Documents.Any(d => !d.IsPersistent))
			{
				if (!this.interaction.AskIfCancelClosing())
				{
					Application.Exit();
				}
			}
			else
			{
				if (!this.interaction.AskIfSaveFilesOnClose())
				{
					Application.Exit();
				}
			}
		}
	}
}